<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['course:CourseUser:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete" v-hasPermi="['course:CourseUser:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['course:CourseUser:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="用户id" align="center" key="userId" prop="userId" />
            <el-table-column label="学生账户" align="center" key="userName" prop="userName" />
            <el-table-column label="学生昵称" align="center" key="nickName" prop="nickName" />
            <el-table-column label="邮箱" align="center" key="email" prop="email" />
            <el-table-column label="手机号" align="center" key="phonenumber" prop="phonenumber" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['course:CourseUser:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改课程信息连接对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-table v-loading="userLoading" :data="unChosenUserList"
                    @selection-change="handleUserSelectionChange">
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column label="用户编号" align="center" key="userId" prop="userId" />
                    <el-table-column label="用户名称" align="center" key="userName" prop="userName"
                        :show-overflow-tooltip="true" />
                    <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName"
                        :show-overflow-tooltip="true" />
                    <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
                </el-table>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listCourseUser, getCourseUser, delCourseUser, addCourseUser, updateCourseUser, listStudent, unChosenList, addCourseUserBatch } from "@/api/course/CourseUser";

export default {
    name: "CourseUser",
    data() {
        return {
            userLoading: true,
            // 未选课的用户
            unChosenUserList: [],
            //
            addCourseUserList: [],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 课程信息连接表格数据
            CourseUserList: [],
            // 选课学生
            studentList: [],
            // 所有学生
            allStudentList: [],
            // 要删除的学生
            deleteStudents: [],
            // 课程Id
            courseId: 0,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                courseId: 0
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
            }
        };
    },
    created() {
        this.courseId = this.$route.params && this.$route.params.courseId;
        if (this.courseId) {
            this.queryParams.courseId = this.courseId
            this.form.courseId = this.courseId
            this.getList();
        }
    },
    methods: {
        /** 查询课程信息连接列表 */
        getList() {
            this.loading = true;
            listStudent(this.queryParams).then(response => {
                this.studentList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
            listStudent().then(response => {
                this.allStudentList = response.rows;
                console.log(this.allStudentList)
            })
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                courseId: this.courseId,
                userId: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.userId)
            for (const id of this.ids) {
                this.deleteStudents.push({ courseId: this.courseId, userId: id });
            }
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        handleUserSelectionChange(selection) {
            let userIds = selection.map(item => item.userId)
            this.addCourseUserList = [];
            for (const id of userIds) {
                this.addCourseUserList.push({ courseId: this.courseId, userId: id });
            }
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.open = true;
            this.title = "添加选课人";
            this.userLoading = true;
            this.unChosenUserList = [];
            unChosenList(this.courseId).then(res => {
                console.log(res)
                this.unChosenUserList = res.data;
                this.userLoading = false;
            })

        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const courseId = row.courseId || this.ids
            getCourseUser(courseId).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改课程信息连接";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    addCourseUserBatch(this.addCourseUserList).then(res => {
                        this.$modal.msgSuccess("新增成功");
                        this.addCourseUserList = [];
                        this.open = false;
                        this.getList();
                    }).catch(() => { this.addCourseUserList = []; });
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            // 如果是单行删除, userId不为空
            let userId = row.userId;
            if (userId) {
                let that = this
                this.$modal.confirm('是否确认删除课程ID为"' + that.courseId + "用户ID为" + userId + '"的关联数据项？').then(function () {
                    console.log(that.courseId, userId)
                    return delCourseUser([{ courseId: that.courseId, userId: userId }]);
                }).then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                }).catch(() => { });
            } else {
                if (this.deleteStudents.length != 0) {
                    let that = this
                    this.$modal.confirm('是否确认删除').then(function () {
                        return delCourseUser(that.deleteStudents);
                    }).then(() => {
                        this.getList();
                        this.$modal.msgSuccess("删除成功");
                    }).catch(() => { });
                }
            }
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('course/CourseUser/export', {
                ...this.queryParams
            }, `CourseUser_${new Date().getTime()}.xlsx`)
        }
    }
};
</script>
